package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;
    @ResponseBody
    @RequestMapping("/empLogin")
    public JsonResult login(String username, String password, HttpSession session){
        try {
            //以用户名为盐为用户密码加密
            Md5Hash md5Hash = new Md5Hash(password,username);
            Employee employee = employeeService.login(username, md5Hash.toString());
            //如果登录成功了,存入session
           // session.setAttribute("USER_IN_SESSION",employee);
            UserContext.setCurrentUser(employee);
            //存入相关的权限
            List<String> expressions = permissionService.selectPermissionByEmpId(employee.getId());

           // session.setAttribute("EXPRESSIONS_IN_SESSION",expressions);

            UserContext.setExpressions(expressions);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            JsonResult jsonResult = new JsonResult();
            jsonResult.setSuccess(false);
            jsonResult.setMsg("账号或者密码错误");
            return jsonResult;
        }
    }

    /**
     * 注销操作
     * @param session
     * @return
     */
    @RequestMapping("/empLogout")
    public String logout(HttpSession session){
        //销毁session
        session.invalidate();
        return "redirect:/login.html";
    }


   @RequestMapping("/nopermission")
    public String nopermission(){
        return "common/nopermission";
    }
}
